package com.aiwiown.snackmq.broker.handler.console;

import com.aiwiown.snackmq.broker.auth.AuthorizationService;
import com.aiwiown.snackmq.cluster.metadata.MetadataManager;
import com.aiwiown.snackmq.common.handler.RequestContext;
import com.aiwiown.snackmq.common.message.Message;
import com.aiwiown.snackmq.common.message.MessageStatus;
import com.aiwiown.snackmq.common.message.MessageType;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UnbindQueueHandler extends AbstractLeaderRequiredConsoleHandler {

    public UnbindQueueHandler(MetadataManager metadataManager, AuthorizationService authorizationService) {
        super(metadataManager, authorizationService);
    }

    @Override
    public MessageType getMessageType() {
        return MessageType.UNBIND_QUEUE_REQUEST;
    }

    @Override
    protected void doHandle(RequestContext ctx, Message request) {
        try {
            String exchangeName = request.getProperty("exchangeName");
            String queueName = request.getTopic();
            String routingKey = request.getProperty("routingKey");

            if (exchangeName == null || queueName == null || routingKey == null) {
                throw new IllegalArgumentException("ExchangeName, QueueName, and RoutingKey properties are required.");
            }

            metadataManager.unbindQueue(queueName, exchangeName, routingKey, status -> {
                if (status.isOk()) {
                    Message response = Message.builder()
                            .type(MessageType.RESPONSE)
                            .messageId(request.getMessageId())
                            .status(MessageStatus.SUCCESS)
                            .build();
                    ctx.writeResponse(response);
                } else {
                    log.error("Failed to unbind queue: {}", status.getErrorMsg());
                    Message response = Message.builder()
                            .type(MessageType.RESPONSE)
                            .messageId(request.getMessageId())
                            .status(MessageStatus.FAILED)
                            .errorMessage(status.getErrorMsg())
                            .build();
                    ctx.writeResponse(response);
                }
            });
        } catch (Exception e) {
            log.error("Error processing unbind queue request", e);
            Message response = Message.builder()
                    .type(MessageType.RESPONSE)
                    .messageId(request.getMessageId())
                    .status(MessageStatus.FAILED)
                    .errorMessage("Internal server error: " + e.getMessage())
                    .build();
            ctx.writeResponse(response);
        }
    }
}